// pages/sendGiftToBUAddress/sendGiftToBUAddress.js
import giftApi from '../../service/giftApi'
let app = getApp()
let codeConfig = {...app.globalData.codeConfig}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    blockChainAddres: '',
    quantity: '',
    sendGiftData: {},
    giftType: '1',
    disabled: true,
    showConfirmFlag: false,
    loading: false,
    noDoubleClick: true, // 防止连点
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      sendGiftData: app.globalData.sendGiftData,
      giftType: options.sendGiftType
    })
  },

  // 输入BU地址
  inpBlockChainAddres(e) {
    this.setData({
      blockChainAddres: e.detail.value.trim()
    })
    this.sendBtnDisabled()
  },

  // 输入数量
  getQuantity(e) {
    this.setData({
      quantity: e.detail.value.trim()
    })
    this.sendBtnDisabled()
  },

  // 扫码
  onScanCode() {
    let that = this
    wx.scanCode({
      success (res) {
        that.setData({
          blockChainAddres: res.result
        })
        that.sendBtnDisabled()
      },
      fail() {
        wx.showToast({
          title: '扫描失败，请重新扫描',
          icon: 'none'
        })
      }
    })
  },

  // 赠送按钮活性
  sendBtnDisabled() {
    if ((this.data.quantity - 0 > 0) && (this.data.blockChainAddres !== '')) {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
  },
  // 赠送按钮
  onSend() {
    let _quantity = this.data.quantity - 0
    let _count = this.data.sendGiftData.count - 0
    if (this.data.blockChainAddres.substr(0, 2) != 'bu') {
      wx.showToast({
        title: '请输入正确的bu地址',
        icon: 'none'
      })
      return false
    }
    if (_quantity > _count) {
      wx.showToast({
        title: '超过可赠送数量，请重新输入',
        icon: 'none'
      })
      return false
    }
    this.setData({
      showConfirmFlag: true
    })
  },

  // 取消赠送
  onCancel() {
    this.setData({
      showConfirmFlag: false
    })
  },

  // 确认赠送
  onOkSend() {
    if (!this.data.noDoubleClick) {
      return false
    }
    this.setData({
      noDoubleClick: false
    })
    let params = {
      couponId: this.data.sendGiftData.couponId,
      sendAmount: this.data.quantity,
      sendType: '2',
      couponType: this.data.sendGiftData.couponType || '5',
      receiver: this.data.blockChainAddres
    }
    giftApi.sendGift(params).then(res => {
      if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        app.globalData.sendGiftOverBackData = '赠送成功'
        this.setData({
          quantity: ''
        })
        wx.navigateBack({
          delta: 1
        })
      } else {
        this.setData({
          noDoubleClick: true,
          showConfirmFlag: false
        })
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }).catch(res => {
      this.setData({
        noDoubleClick: true,
        showConfirmFlag: false
      })
      console.log(res);
    })
  }
})